package cn.hengzhu.main_manager.web.controller;

import cn.hengzhu.main_manager.repository.dao.ManageCompMapper;
import cn.hengzhu.main_manager.repository.dao.ManagePermissionMapper;
import cn.hengzhu.main_manager.repository.dao.ManageRolesMapper;
import cn.hengzhu.main_manager.repository.dao.ManageUserMapper;
import cn.hengzhu.main_manager.repository.domain.*;
import cn.hengzhu.main_manager.repository.param.ManagerListParam;
import cn.hengzhu.main_manager.repository.param.UpateRoleParam;
import cn.hengzhu.main_manager.repository.vo.RoleListVO;
import cn.hengzhu.main_manager.service.ManageCaseBoxService;
import cn.hengzhu.main_manager.utils.AjaxResult;
import cn.hengzhu.main_manager.utils.LayUiResultJson;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;
import cn.hengzhu.main_manager.utils.config.gzh.WeiXinConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/main")
public class RoleController {
	@Autowired
	private ManageUserMapper manageUserMapper;
	@Autowired
	private ManageRolesMapper manageRolesMapper;
	@Autowired
	private ManageCompMapper manageCompMapper;
	@Autowired
	private ManagePermissionMapper managePermissionMapper;
	@Autowired
	private ManageCaseBoxService manageCaseBoxService;

	/**
	 * 角色列表
	 * 
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getRoleList", method = RequestMethod.GET)
	public LayUiResultJson<RoleListVO> getRoleList(ManagerListParam param) {
		List<RoleListVO> list = new ArrayList<>();
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();

		PageHelper.startPage(param.getPage(), param.getLimit(), true);
		List<ManageRoles> roleList = manageRolesMapper.getAllRolesByComId(compId);
		PageInfo<ManageRoles> pageInfo = new PageInfo<>(roleList);
		long count = pageInfo.getTotal();
		List<Integer> compIds = roleList.stream()
				.collect(Collectors.mapping(ManageRoles::getCompId, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());
        
		ManageCompExample example = new ManageCompExample();
		example.createCriteria().andCompIdIn(compIds);
		List<ManageComp> compList = manageCompMapper.selectByExample(example);

		Map<Integer, ManageComp> CompByIdMap = compList.stream()
				.collect(Collectors.toMap(ManageComp::getCompId, a -> a));

		roleList.stream().forEach(a -> {
			RoleListVO roleListVO = new RoleListVO();
			roleListVO.setRoleId(a.getRoleId());
			roleListVO.setDes(a.getDes());
			roleListVO.setRoleName(a.getName());
			roleListVO.setPercent(a.getPercent());
			Integer compId2 = a.getCompId();
			if (compId2 == 0) {
				roleListVO.setCompName("恒铸");
			} else {
				ManageComp manageComp = CompByIdMap.get(compId2);
				if (manageComp != null) {
					roleListVO.setCompName(manageComp.getCompName());
				} else {
					roleListVO.setCompName("该公司已被删除");

				}

			}
			String permissions = a.getPermissions();
			List<String> asList = Arrays.asList(permissions.split(","));
			roleListVO.setPermissionIds(asList);
			list.add(roleListVO);
		});

		LayUiResultJson<RoleListVO> result = new LayUiResultJson<>(count, list);
		return result;
	}

	/**
	 * 修改角色信息
	 */
	@ResponseBody
	@RequestMapping(value = "/upateRole", method = RequestMethod.POST)
	@SystemControllerLog(description = "修改角色信息")
	public AjaxResult upateRole(UpateRoleParam param) {
		ManageUser user = UserContext.getUser();
		Integer ownRoleId = user.getRoleId();
		Integer roleId = param.getRoleId();
		ManageRoles otherRole = manageRolesMapper.selectByPrimaryKey(roleId);
		ManageRoles ownRole = manageRolesMapper.selectByPrimaryKey(ownRoleId);
		String otherPermissions = otherRole.getPermissions();
		String ownPermissions = ownRole.getPermissions();
		List<String> otherpermissionList = Arrays.asList(otherPermissions.split(","));
		List<String> ownpermissionList = Arrays.asList(ownPermissions.split(","));
		// 修改后的权限
		String updateAfterpermissions = param.getPermissions();
		List<String> updateAfterpermissionList = Arrays.asList(updateAfterpermissions.split(","));
		List<Integer> codesInteger = updateAfterpermissionList.stream().map(Integer::parseInt)
				.collect(Collectors.toList());
		ManageRoles manageRoles = new ManageRoles();
		manageRoles.setDes(param.getDes());
		manageRoles.setRoleId(param.getRoleId());
		manageRoles.setName(param.getRoleName());
		manageRoles.setPermissions(param.getPermissions());
		manageRoles.setPercent(param.getPercent());

		if (ownpermissionList.containsAll(otherpermissionList)) {
			ManagePermissionExample permissionExample = new ManagePermissionExample();
			permissionExample.createCriteria().andIdIn(codesInteger);
			List<ManagePermission> permissionsByIds = managePermissionMapper.selectByExample(permissionExample);
			List<String> snList = permissionsByIds.stream()
					.collect(Collectors.mapping(ManagePermission::getSn, Collectors.toList()));
			try {
				if (snList.contains(WeiXinConst.PERMISSION_OPENBOX)) {
					manageRolesMapper.updateByPrimaryKeySelective(manageRoles);
				} else {
					manageCaseBoxService.clearBind(manageRoles);
				}
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("修改失败");
			}
		} else {
			return new AjaxResult("此账户权限高于您，不可修改");
		}

	}

	/**
	 * 添加角色信息
	 */
	@SystemControllerLog(description = "添加角色")
	@ResponseBody
	@RequestMapping(value = "/addRole", method = RequestMethod.POST)
	public AjaxResult addRole(UpateRoleParam param) {
		ManageRoles manageRoles = new ManageRoles();
		manageRoles.setDes(param.getDes());
		manageRoles.setName(param.getRoleName());
		manageRoles.setPermissions(param.getPermissions());
		manageRoles.setCreateTime(new Date());
		manageRoles.setCompId(param.getCompId());
		manageRoles.setPercent(param.getPercent());
		ManageRolesExample manageRolesExample = new ManageRolesExample();
		manageRolesExample.createCriteria().andNameEqualTo(param.getRoleName()).andCompIdEqualTo(param.getCompId());
		List<ManageRoles> selectByExample = manageRolesMapper.selectByExample(manageRolesExample);
		if (selectByExample.isEmpty()) {
			try {
				manageRolesMapper.insert(manageRoles);
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("添加失败");
			}
		} else {
			return new AjaxResult("角色名重复");

		}
	}

	/**
	 * 删除角色信息
	 */
	@SystemControllerLog(description = "删除角色信息")
	@ResponseBody
	@RequestMapping(value = "/deleteRole", method = RequestMethod.GET)
	public AjaxResult deleteRole(@ApiParam(required = true, name = "roleId", value = "角色Id") Integer roleId) {

		ManageUserExample example = new ManageUserExample();
		example.createCriteria().andRoleIdEqualTo(roleId);
		List<ManageUser> userList = manageUserMapper.selectByExample(example);

		if (userList.isEmpty()) {
			try {
				manageRolesMapper.deleteByPrimaryKey(roleId);
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("删除失败");
			}
		} else {
			return new AjaxResult("此角色正在使用，不能删除");
		}
	}

}
